package com.TP.www.service.impl;


import com.TP.www.dao.impl.CustomerDAO;
import com.TP.www.dao.impl.MerchantDAO;
import com.TP.www.po.Customer;
import com.TP.www.po.Merchant;
import com.TP.www.po.User;
import com.TP.www.service.LogInPort;
import com.TP.www.servlet.CustomerMenu;
import com.TP.www.servlet.MerchantMenu;
import com.TP.www.util.Md5;

import java.util.List;

import static com.TP.www.constant.Constant.SYS_SC;
import static com.TP.www.constant.Constant.loginUser;
/**
 * @author 邱彦祥
 * 登入功能实现类
 */
public class LogIn implements LogInPort {
    MerchantDAO merchantDAO = new MerchantDAO();
    CustomerDAO customerDAO = new CustomerDAO();
    /**
     * 登入
     */
    @Override
    public void login() {
        while (true) {
            System.out.println("请输入用户名：");
            String loginName = SYS_SC.nextLine();
            System.out.println("请输入密码：");
            String passWord = SYS_SC.nextLine();

            //根据用户名和密码进行匹配登入
            User user = getUserByLogInNameAndPassWord(loginName,passWord);
            if(user != null){
                loginUser = user;
                //若该用户为顾客
                if(user instanceof Customer){
                    CustomerMenu.showCustomerMain();
                }
                //若该用户为商家
                else if(user instanceof Merchant){
                    MerchantMenu.showMerchantMain();
                }
                return;
            }else{
                System.out.println("用户名或密码输入错误！");
            }
        }
    }

    /**
     * 验证登入
     * @param loginName 登入名
     * @param passWord 密码
     * @return 成功登入用户
     */
    @Override
    public User getUserByLogInNameAndPassWord(String loginName, String passWord){
        Md5 md = new Md5();
        String secretPassword = md.start(passWord).toUpperCase();
        String customerSql = "select * from customer where name = ? and password = ?;";
        String merchantSql = "select * from merchant where name = ? and password = ?;";
        List<Customer> customer = customerDAO.executeQuery(customerSql,loginName,secretPassword);
        List<Merchant> merchant = merchantDAO.executeQuery(merchantSql,loginName,secretPassword);
        if(!customer.isEmpty()){
            return customer.get(0);
        }else if (!merchant.isEmpty()){
            return merchant.get(0);
        }
        return null;
    }
}
